import { pannerOptions } from "./@types";
export class creatTrack {
    private readonly audioElement: HTMLAudioElement; // 可控节点

    private readonly audioTrack:AudioContext // 轨道对象
    private readonly gainNode:GainNode // 轨道音量节点
    private readonly analogyNode:AnalyserNode
    private gain: number | undefined // 轨道音量
    private mute:boolean // 轨道静音

    constructor(
        data:any,
        gain:number = 1,
        mute:boolean = false,
    ) {
        this.audioTrack = new AudioContext()
        this.mute = !mute

        this.gainNode = this.audioTrack.createGain()
        this.analogyNode = this.audioTrack.createAnalyser()
        this.analogyNode.fftSize = 512 // 傅立叶系数
        this.setGain(gain)
        this.toggleMute()
        this.audioElement = new Audio();// 创建音频标签元素
        this.audioElement.crossOrigin = "anonymous";// 设置跨域
        this.setMusic(data)// 设置音乐
        const mediaElementSource = this.audioTrack.createMediaElementSource(this.audioElement)
        mediaElementSource.connect(this.gainNode) // 使用gain控制
        this.gainNode.connect(this.analogyNode) // 分析仪
        this.analogyNode.connect(this.audioTrack.destination) // 输出
    }

    // 设置音量
    setGain(gain:number) {
        this.gain = gain
        this.gainNode.gain.value = gain
    }
    // 设置静音
    toggleMute() {
        this.mute = !this.mute
        this.mute ? this.gainNode.gain.value = 0 : this.setGain(this.gain ?? 0)
    }
    // 播放
    play() {
        this.audioElement.play()
    }
    // 暂停
    pause() {
        this.audioElement.pause()
    }
    // 停止
    stop() {
        this.audioElement.pause()
        this.audioElement.currentTime = 0
    }
    // 设置资源
    setMusic(data:any) {
        if(!data) return
        this.stop()
        this.audioElement.src = data
    }
    // 时间监控
    handleTimeUpdate(callback:Function) {
        this.audioElement.addEventListener('timeupdate', (res) => {
            // const audioArray = new Uint8Array( this.analogyNode.frequencyBinCount)
            // this.analogyNode.getByteFrequencyData(audioArray)
            // console.log(audioArray)
            const {currentTime,duration} = this.audioElement
            callback({currentTime,duration},res)
        })
    }
    // 状态监控
    handleStateChange(callback:Function) {
        this.audioElement.addEventListener('play', (res) => callback(res))
        this.audioElement.addEventListener('pause', (res) => callback(res))
        this.audioElement.addEventListener('ended', (res) => callback(res))
        this.audioElement.addEventListener('error', (res) => callback(res))
    }
    // 设置时间
    setCurrentTime(time:number) {
        this.audioElement.currentTime = time
    }
    destroy(callback:Function){
        this.audioTrack.close().then(res => callback && callback(res))
    }
}
